package com.gmail.at.controller;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.gmail.at.form.PassengerGrid;
import com.gmail.at.model.Passenger;
import com.gmail.at.service.PassengerService;
import com.google.common.collect.Lists;

@RequestMapping("/passengers")
@Controller
public class PassengerController {

	final Logger logger = LoggerFactory.getLogger(PassengerController.class);

	@Autowired
	private PassengerService passengerService;

	@Autowired
	MessageSource messageSource;

	@RequestMapping(method = RequestMethod.GET)
	public String list(Model uiModel) {
		logger.info("Listing passengers");
		Passenger passenger = new Passenger();
		uiModel.addAttribute("passenger", passenger);
		return "passengers/list";
	}
	
	@RequestMapping(value = "/listgrid", method = RequestMethod.GET, produces = "application/json")
	@ResponseBody
	public PassengerGrid listGrid(
			@RequestParam(value = "page", required = false) Integer page,
			@RequestParam(value = "rows", required = false) Integer rows,
			@RequestParam(value = "sidx", required = false) String sortBy,
			@RequestParam(value = "sord", required = false) String order) {
		logger.info("Listing passengers for grid with page: {}, rows: {}", page,
				rows);
		logger.info("Listing passengers for grid with sort: {}, order: {}",
				sortBy, order);
		Sort sort = null;
		String orderBy = sortBy;
		if (orderBy != null && orderBy.equals("birthDateString")) {
			orderBy = "passengerDateOfBirth";
		}	
		if (orderBy != null && order != null) {
			if (order.equals("desc")) {
				sort = new Sort(Sort.Direction.DESC, orderBy);
			} else
				sort = new Sort(Sort.Direction.ASC, orderBy);
		}
		PageRequest pageRequest = null;
		if (sort != null) {
			pageRequest = new PageRequest(page - 1, rows, sort);
		} else {
			pageRequest = new PageRequest(page - 1, rows);
		}
		Page<Passenger> passengerPage = passengerService.findAllByPage(pageRequest);
		PassengerGrid passengerGrid = new PassengerGrid();
		passengerGrid.setCurrentPage(passengerPage.getNumber() + 1);
		passengerGrid.setTotalPages(passengerPage.getTotalPages());
		passengerGrid.setTotalRecords(passengerPage.getTotalElements());
		passengerGrid.setPassengerData(Lists.newArrayList(passengerPage.iterator()));
		return passengerGrid;
	}
	

	@RequestMapping(value = "/{passengerID}", params = "delete", method = RequestMethod.GET)
	public @ResponseBody String delete(@PathVariable("passengerID") Integer id, Model uiModel) {
		return passengerService.delete(id);
	}
	
	@RequestMapping(value = "/{passengerID}", params = "form", method = RequestMethod.POST)
	public @ResponseBody String update(@Valid Passenger passenger, @PathVariable("passengerID") Integer id, BindingResult bindingResult,
			Model uiModel, HttpServletRequest httpServletRequest,
			RedirectAttributes redirectAttributes, Locale locale) {
		logger.info("Updating passengers");
		if (bindingResult.hasErrors()) {
			return "Invalid passenger information (check fields)";
		}
		Passenger temp = passengerService.findById(id);
		if (temp != null) {
			if (temp.getLogin().equals(passenger.getLogin())) {
				temp.setPassengerDateOfBirth(passenger.getPassengerDateOfBirth());
				temp.setPassengerName(passenger.getPassengerName());
				temp.setPassengerSurname(passenger.getPassengerSurname());
				temp.setPassword(passenger.getPassword());
				passengerService.save(temp);
				return "ok";
			}
			if (temp.getPassengerName().equals(passenger.getPassengerName()) && temp.getPassengerSurname().equals(passenger.getPassengerSurname())) {
				temp.setPassengerDateOfBirth(passenger.getPassengerDateOfBirth());
				temp.setPassword(passenger.getPassword());
				temp.setLogin(passenger.getLogin());
				passengerService.save(temp);
				return "ok";
			}
			temp.setPassengerDateOfBirth(passenger.getPassengerDateOfBirth());
			temp.setPassengerName(passenger.getPassengerName());
			temp.setPassengerSurname(passenger.getPassengerSurname());
			temp.setPassword(passenger.getPassword());
			temp.setLogin(passenger.getLogin());
			String result = passengerService.registration(temp);
			if (result.equals("ok")) {	
				return "ok";
			} else {
				return result;
			}
		} else {
			return "Passenger with this id wasn't found, update your list";
		}
	}

	@RequestMapping(method = RequestMethod.POST)
	public @ResponseBody String create(@Valid Passenger passenger,
			BindingResult bindingResult, Model uiModel,
			HttpServletRequest httpServletRequest,
			RedirectAttributes redirectAttributes, Locale locale) {
		logger.info("Creating passenger");
		if (bindingResult.hasErrors()) {
			return "Invalid passenger information (check fields)";
		}
		String result = passengerService.registration(passenger);
    	if (result.equals("ok")) {
    		return "ok";   
    	} else {
			return result;
    	}
	}
}
